package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.SportRecordRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.widget.CandlestickChart
import com.module.overview.R
import java.util.Calendar
import java.util.concurrent.TimeUnit

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/10
 *
 * 描述：体征-心率卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSignsHrCardProvider(mCalendar: CalendarDay?,
                            override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS_HR,
                            override val layoutId: Int = R.layout.overview_signs_hr_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    var tvAverageHr: TextView? = null
    var tvLastTime: TextView? = null
    var tvTheDayAverage: TextView? = null
    var tvTheDayScope: TextView? = null
    var tvMeasure: TextView? = null
    var candlestickChart: CandlestickChart? = null

    var mCalendar = mCalendar
    private var curTime = mCalendar?.toCalendar()?.timeInMillis?:0

    var measureResult :Number = -1

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        candlestickChart?.setYAxisStages(
//            floatArrayOf(40f, 80f, 90f, 120f), // 阶段分界点
            floatArrayOf(40f, 80f, 120f), // 阶段分界点

        )
//        // 在代码中设置数据
//        candlestickChart?.setData(stressData)
//
//        candlestickChart?.setAverageData(averageDataValues)

        getTheDayHr()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvAverageHr = viewHolder.getView(R.id.tvAverageHr)
        tvLastTime = viewHolder.getView(R.id.tvLastTime)
        tvTheDayAverage = viewHolder.getView(R.id.tvTheDayAverage)
        tvTheDayScope = viewHolder.getView(R.id.tvTheDayScope)

        tvMeasure = viewHolder.getView(R.id.tvMeasure)
        candlestickChart = viewHolder.getView(R.id.candlestickChart)
        // 设置触摸监听
        candlestickChart?.setOnBarTouchListener(object : CandlestickChart.OnBarTouchListener {
            override fun onBarTouched(barIndex: Int, minValue: Float, maxValue: Float, timeLabel: String, extStr: String) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
//                viewHolder.setText(R.id.tvAverageHr, (minValue+((maxValue-minValue)/2)).toInt().toString())
            }

            override fun onAverageLineTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                tvAverageHr?.text = if (extStr.isNullOrEmpty()) getString(R.string.common_rail_unit) else extStr
                tvLastTime?.text = timeLabel
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                tvAverageHr?.text = if (measureResult.toInt() <= -1) getString(R.string.common_rail_unit) else measureResult.toString()
                tvLastTime?.text = getString(R.string.common_last_time_hint)
            }
        })
        viewHolder.setVisible(R.id.tvMeasure, (mCalendar?.dateName == getString(R.string.common_today_hint)))
        LiveEventBus.get(KeyEvents.KEY_OV_SET_HR_MEASUREMENT_LISTENER).post(this)
        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取当天心率
     */
    fun getTheDayHr(){
        if (curTime <=0) return

        doOnIOThread {
            //当天心率
            HeartRateRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@let

//                val listItStr = JsonUtils.toJson(originalListIt)

                // 创建48个时间区间块的CusChartData数组
                val stressListData = mutableListOf<CusChartData>()

                // 获取curTime当天的0点时间戳
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = curTime
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
                calendar.set(Calendar.MILLISECOND, 0)
                val startOfDay = calendar.timeInMillis

                for (index in 0 until 48) {
                    val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
                    val intervalStartTime = startOfDay + timeOffset
                    val intervalEndTime = startOfDay + timeOffset + (30 * 60 * 1000L) // 加30分钟作为结束时间

                    // 查找在当前时间区间内的心率数据
                    val dataInInterval = originalListIt.filter { heartRateData ->
                        heartRateData.createdTime in intervalStartTime until intervalEndTime
                    }

                    var mValue = 0f
                    var extStr = ""

                    if (dataInInterval.isNotEmpty()) {
                        // 计算平均值
                        val heartRateValues = dataInInterval.map { it.heartRate }
                        val average = heartRateValues.average().toFloat()
                        mValue = average

                        // 生成extStr，格式为"最小值~最大值"
                        val minValue = heartRateValues.minOrNull() ?: 0
                        val maxValue = heartRateValues.maxOrNull() ?: 0
                        extStr = "$minValue~$maxValue"
                    } else {
                        // 如果区间内没有数据，设置为0
                        mValue = -1f
                        extStr = ""
                    }

                    stressListData.add(
                        CusChartData(
                            createdTime = intervalStartTime,
                            endTime = intervalEndTime,
                            mValue = mValue,
                            minValue = -1f,
                            exStr = extStr,
                            dayNum = 0
                        )
                    )
                }

                val stressListDataStr = JsonUtils.toJson(stressListData)
                val minTemp = ((originalListIt.minOfOrNull { it.heartRate } ?: 30f).toFloat())
                val maxTemp = ((originalListIt.maxOfOrNull { it.heartRate } ?: 125f).toFloat())
                val theDayAverage = if (originalListIt.isNotEmpty()) {//当日平均
                    originalListIt.map { it.heartRate }.average().toInt().toString()
                } else {
                    getString(R.string.common_rail_unit)
                }

                val latestHeartRate = originalListIt.maxByOrNull { it.createdTime }

                doOnUiThread {

                    latestHeartRate?.let {latestHeartRateIt->
                        measureResult = latestHeartRateIt.heartRate
                        tvAverageHr?.text = measureResult.toString()
                    }

                    tvTheDayAverage?.text = theDayAverage
                    tvTheDayScope?.text = "${minTemp.toInt()}~${maxTemp.toInt()}"

                    // 设置Y轴阶段
                    candlestickChart?.setYAxisStages(
                        floatArrayOf(if(minTemp-10f <=0) 0f else minTemp-10f, ((maxTemp-minTemp)/2).toInt()+minTemp, maxTemp+10f), // 阶段分界点
                    )

                    candlestickChart?.setDrawBackgroundBarsByDataValues(false)

                    // 通知图表更新数据
                    candlestickChart?.setAverageData(stressListData)
                }

                getTheDaySportsData(stressListData)
            }
        }
    }

    /**
     * 获取当天运动信息
     */
    fun getTheDaySportsData(stressListData : MutableList<CusChartData>){
        doOnIOThread {
            SportRecordRepo.instance.findAllByDay(TimeUtils.getTimeDateLong())?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@let
//                val listItStr = JsonUtils.toJson(originalListIt)

                // 遍历运动数据记录数组
                originalListIt.forEach { beanIt->
                    // 遍历stressListData中的每条数据
                    for (i in stressListData.indices) {
                        val stressBeanIt = stressListData[i]
                        // 判断stressListData每天数据的createdTime时间戳是否在beanIt的startTs和endTs范围内
                        if (stressBeanIt.createdTime in beanIt.startTs until beanIt.endTs) {
                            // 如果在范围内，将该条stressBeanIt.selectBg设置为true
                            stressListData[i] = stressBeanIt.copy(selectBg = true)
                        }
                    }
                }

                doOnUiThread {
                    // 通知图表更新数据
                    candlestickChart?.setAverageData(stressListData)
                }
            }
        }
    }
}